package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.azureAD.AzureADTool;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.RolesService;
import com.cci.kangdao.service.ScanRecordService;
import com.cci.kangdao.service.SyncEsnAndUserId;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author William Du
 * @date 2019/4/30
 */
@Service
public class RolesServiceImpl implements RolesService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Resource
	private CompanyTDao companyTDao;
	@Resource
	private ServiceStationDao serviceStationDao;
	@Resource
	private RolesDao rolesDao;
	@Resource
	private UserTDao userTDao;
	@Resource
	private RolesTDao rolesTDao;
	@Resource
	private RolesOrderTDao rolesOrderTDao;
	@Resource
	private RolesOrderHandlerRelationTDao rolesOrderHandlerRelationTDao;
	@Resource
	private RelationShipTDao relationShipTDao;
	@Resource
	private RolesNotifyRecordTDao rolesNotifyRecordTDao;
	@Resource
	private RolesHandleTDao rolesHandleTDao;
	@Resource
	private CompanyUserGroupRelationDao companyUserGroupRelationDao;
	@Resource
	private RedisClientUtils redisClientUtils;
	@Resource
	private LoginDao loginDao;
	@Resource
	private PropertiesUtils propertiesUtils;
	@Resource
	private SSRepairTDao ssRepairTDao;
	@Resource
	private UserGroupSubTDao userGroupSubTDao;
	@Resource
	private RoleChannelTDao roleChannelTDao;
	@Resource
	private PositionUserTDao positionUserTDao;
	@Resource
	private ScanRecordService scanRecordService;
	@Resource
	private FotonPositionTDao fotonPositionTDao;
	@Resource
	private UserGroupHasRoleDao userGroupHasRoleDao;
	@Resource
	private CipServiceApi cipServiceApi;
    @Resource
    private UserChannelTMapper userChannelTMapper;
	@Resource
	private ExternalDataSynchroService externalDataSynchroService;
	@Resource
	private SyncEsnAndUserId syncEsnAndUserId;
	@Resource
	private CipFleetService cipFleetService;

	private Pattern WWID_PATTERN = Pattern.compile("^([A-Za-z]{2})([0-9A-Za-z]{3})$");

	private static final String MASTER_ROLENO = "R0041";// 服务商站长

	private static final String SERVICE_ENGINEER_ROLE_NO = "R0013";// 服务工程师

	@Override
	public void getOrganizationList(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String type = (String) map.get("type");
		List<Map<String, Object>> responseMapList = new ArrayList<>();
		if ("1".equals(type)) {
			List<CompanyT> companyTList = companyTDao.getCompanyList();
			if (CollectionUtils.isNotEmpty(companyTList)) {
				for (CompanyT companyT : companyTList) {
					Map<String, Object> companyMap = new HashMap<>();
					companyMap.put("organizationId", companyT.getId());
					companyMap.put("organizationName", companyT.getCompanyName());
					companyMap.put("companyNo", companyT.getCompanyNo());
					// 如果是康明斯，增加子用户组数据
					if (companyT.getCompanyNo().equalsIgnoreCase("CCI")) {
						List<Map<String, Object>> subUserGroupMapList = new ArrayList<>();
						List<Map<String, Object>> subMapList = userGroupSubTDao
								.getSubUserGroupByCompanyId(companyT.getId(), 1);
						if (CollectionUtils.isNotEmpty(subMapList)) {
							subMapList.forEach(subMap -> {
								Map<String, Object> subUserGroupMap = new HashMap<>();
								subUserGroupMap.put("subUserGroupId", MapUtils.getLong(subMap, "ID"));
								subUserGroupMap.put("subUserGroupName", MapUtils.getString(subMap, "GroupName"));
								subUserGroupMapList.add(subUserGroupMap);
							});
						}
						companyMap.put("subUserGroupList", subUserGroupMapList);
					}
					responseMapList.add(companyMap);
				}
			}
		} else if ("2".equals(type)) {
			String name = (String) map.get("organizationName");
			if (StringUtils.isNotEmpty(name)) {
				name = "%" + name + "%";
				List<ServiceStationT> serviceStationTList = serviceStationDao
						.getCategoryServiceStationListLikeName(name, 1);
				if (CollectionUtils.isNotEmpty(serviceStationTList)) {
					for (ServiceStationT serviceStationT : serviceStationTList) {
						Map<String, Object> serviceStationMap = new HashMap<>();
						serviceStationMap.put("organizationId", serviceStationT.getId());
						serviceStationMap.put("organizationName", serviceStationT.getStationname());
						List<String> companyNosList = companyTDao.getServiceChannelByStationId(serviceStationT.getId())
								.stream().filter(companyT -> Optional.ofNullable(companyT.get("CompanyNo")).isPresent())
								.map(companyT -> companyT.get("CompanyNo").toString()).collect(Collectors.toList());
						serviceStationMap.put("companyNo", String.join(",", companyNosList));
						responseMapList.add(serviceStationMap);
					}
				}
			}
		} else {
			String name = (String) map.get("organizationName");
			if (StringUtils.isNotEmpty(name)) {
				List<ServiceStationT> serviceStationTList = serviceStationDao
						.getCategoryServiceStationListLikeName(name, 2);
				if (CollectionUtils.isNotEmpty(serviceStationTList)) {
					for (ServiceStationT serviceStationT : serviceStationTList) {
						Map<String, Object> serviceStationMap = new HashMap<>();
						serviceStationMap.put("organizationId", serviceStationT.getId());
						serviceStationMap.put("organizationName", serviceStationT.getStationname());
						List<String> companyNosList = companyTDao.getServiceChannelByStationId(serviceStationT.getId())
								.stream().filter(companyT -> Optional.ofNullable(companyT.get("CompanyNo")).isPresent())
								.map(companyT -> companyT.get("CompanyNo").toString()).collect(Collectors.toList());
						serviceStationMap.put("companyNo", String.join(",", companyNosList));
						responseMapList.add(serviceStationMap);
					}
				}
			}
		}
		ParameterTool.writeSuccessResponse(response, responseMapList);
	}

	@Override
	public void checkOrganization(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			String type = (String) map.get("type");
			Integer companyType = MapUtils.getInteger(map, "companyType");
			String organizationName = (String) map.get("organizationName");
			String userId = (String) map.get("userId");
			Map<String, Object> responseMap = new HashMap<>();
			UserT userT = null;
			if (StringUtils.isNotEmpty(userId)) {
				userId = AESTool.decryptString(userId);
				userT = userTDao.selectById(Long.valueOf(userId));
			}

			if (type.equals("1")) {
				CompanyT companyT = companyTDao.getCompanyInfoByCompanyName(organizationName);
				if (null == companyT) {
					ParameterTool.writeResponse(response, 1, "企业不存在，请检查是否正确");
					return;
				}
				// 校验传入组织类型和查询组织类型是否一致
				if (null != companyType) {
					Map<String, Object> channelMap = roleChannelTDao.getRoleChannelByCompanyType(companyType);
					if (MapUtils.isEmpty(channelMap)) {
						ParameterTool.writeResponse(response, 2, "组织名称与申请类型不符，请检查是否正确");
						return;
					} else {
						Long companyId = MapUtils.getLong(channelMap, "CompanyId", 0L);
						if (!companyId.equals(companyT.getId())) {
							ParameterTool.writeResponse(response, 2, "组织名称与申请类型不符，请检查是否正确");
							return;
						}
					}
				}
				// 通过企业获取企业角色列表
				List<Map<String, Object>> roleMapList = rolesDao.getCompanyRoles(companyT.getId());
				responseMap.put("organizationId", companyT.getId());
				responseMap.put("organizationType", 1);
				// 筛选角色列表
				List<Map<String, Object>> rolesResponseList = filterRoleList(userT, companyT.getId(), "1", roleMapList);
				responseMap.put("roleList", rolesResponseList);
				ParameterTool.writeSuccessResponse(response, responseMap);
			} else {
				ServiceStationT serviceStationT = serviceStationDao.getServiceStationByStationName(organizationName);
				if (null == serviceStationT) {
					ParameterTool.writeResponse(response, 1, "服务商不存在，请贵公司站长联系康明斯维护服务站信息");
					return;
				}
				responseMap.put("organizationId", serviceStationT.getId());
				responseMap.put("organizationType", 2);
				Map<String, Object> serviceStationIdMap = new HashMap<>();
				serviceStationIdMap.put("ServiceStationID", serviceStationT.getId());
				List<UserT> stationMasterList = userTDao.getUserTByServiceStationId(serviceStationIdMap);
				if (CollectionUtils.isNotEmpty(stationMasterList)) {
					responseMap.put("hasStationMaster", 1);
				} else {
					responseMap.put("hasStationMaster", 0);
				}
				List<Map<String, Object>> roleMapList = rolesDao.getServiceStationRoles(serviceStationT.getId());
				// 筛选角色列表
				List<Map<String, Object>> rolesResponseList = filterRoleList(userT, serviceStationT.getId(), "2",
						roleMapList);
				responseMap.put("roleList", rolesResponseList);
				ParameterTool.writeSuccessResponse(response, responseMap);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ParameterTool.writeErrorResponse(response);
		}
	}

	private List<Map<String, Object>> filterRoleList(UserT userT, Long organizationId, String type,
			List<Map<String, Object>> roleMapList) {
		List<Map<String, Object>> filterRoleList = new ArrayList<>();
		Boolean isCurrentOrganization = Boolean.FALSE;
		// 当前拥有角色列表
		List<Long> roleIdList = new ArrayList<>();
		if (null != userT) {
			if (type.equals("1")) {
				if (userT.getCompanyId() == organizationId) {
					isCurrentOrganization = Boolean.TRUE;
				}
			} else {
				if (userT.getServiceStationID() == organizationId) {
					isCurrentOrganization = Boolean.TRUE;
				}
			}
			if (isCurrentOrganization) {
				List<Map<String, Object>> currentRoleMapList = loginDao.getUserRoles(Long.valueOf(userT.getId()));
				if (CollectionUtils.isNotEmpty(currentRoleMapList)) {
					currentRoleMapList.forEach(roleEntity -> roleIdList.add((Long) roleEntity.get("ID")));
				}
			}
		}
		if (CollectionUtils.isNotEmpty(roleMapList)) {
			// 若申请角色的组织为当前组织
			if (isCurrentOrganization) {
				roleMapList.forEach(roleEntity -> {
					Long roleId = (Long) roleEntity.get("ID");
					// 过滤已拥有角色，只输出未拥有角色
					if (!roleIdList.contains(roleId)) {
						Map<String, Object> roleMaps = new HashMap<>();
						roleMaps.put("roleId", roleEntity.get("ID"));
						roleMaps.put("roleName", roleEntity.get("RolesName"));
						filterRoleList.add(roleMaps);
					}
				});
			} else {
				// 非当前组织角色，输出所有角色信息
				roleMapList.forEach(roleEntity -> {
					Map<String, Object> roleMaps = new HashMap<>();
					roleMaps.put("roleId", roleEntity.get("ID"));
					roleMaps.put("roleName", roleEntity.get("RolesName"));
					filterRoleList.add(roleMaps);
				});
			}
		}
		return filterRoleList;
	}

	@Override
	@Transactional
	public void applyRole(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		UserT userT = UserThreadLocal.get();
		UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userT.getId(),"2");
		try {
			// 校验手机验证码
			String phone = MapUtils.getString(map, "phone");
			String verifyCode = MapUtils.getString(map, "verifyCode");
			if (!validateVerifyCode(phone, verifyCode)) {
				ParameterTool.writeErrorResponse(response, -6);
				return;
			}
			if (null != userChannelT) {
				ParameterTool.writeErrorResponse(response, -97,"老友汇用户不可更改角色");
				return;
			}
			Long organizationId = Long.valueOf(map.get("organizationId").toString());
			Integer organizationType = Integer.valueOf(map.get("organizationType").toString());
			String organizationName = map.get("organizationName").toString();

			Long roleId = Long.valueOf(map.get("roleId").toString());
			String employeeNum = MapUtil.getMapValue(map, "employeeNum", null);
			Long subUserGroupId = MapUtils.getLong(map, "subUserGroupId");
			// 获取是否存在待申请记录
			RolesOrderT rolesOrderT = rolesOrderTDao.selectNoConfirmOrder(userT.getId());
			if (null != rolesOrderT) {
				RolesT rolesT = rolesTDao.getRolesById(rolesOrderT.getRoleId());
				ParameterTool.writeResponse(response, 5, "您申请的" + rolesT.getRolesName() + "角色，尚在待审核流程，请稍后再试。");
				return;
			}
			// 获取用户组数据
			Long userGroupId = getUserGroupId(organizationId, organizationType);
			if (null == userGroupId) {
				ParameterTool.writeResponse(response, 3, "查无用户渠道，请联系管理员维护渠道信息");
				return;
			}
			// 查询审核人信息
			List<UserT> handlerList = null;
			RolesT rolesT = rolesTDao.getRolesById(roleId);
			if (null != rolesT && rolesT.getIsApproval().equals(1)) {
				handlerList = getHandlerList(organizationId, organizationType, userGroupId, roleId);
				if (CollectionUtils.isEmpty(handlerList)) {
					ParameterTool.writeResponse(response, 4, "该角色暂未配置审批人，请联系相关人员维护信息");
					return;
				}
			}

			// 加锁处理，避免发生多次注册。
			if (!redisClientUtils.lock("applyRole-" + userT.getUserName(), 60L)) {
				ParameterTool.writeErrorResponse(response, -98);
				return;
			}

			Integer applyType = MapUtils.getInteger(map, "applyType", 1);

			// 增加权限申请订单
			if (NumberUtils.isPositiveNum(rolesT.getIsApproval())) {
				Map<String, Object> responseMap = new HashMap<>();
				// 当用户内部内部员工，并且申请角色为服务工程师时，直接通过
				if (userT.getType().equals(2) && rolesT.getRolesNo().equals(SERVICE_ENGINEER_ROLE_NO)) {
					RolesOrderT orderT = initRoleOrder(userT.getId(), roleId, rolesT.getRolesName(), organizationId,
							organizationName, organizationType, employeeNum, subUserGroupId, 2, applyType);
					handleOrder(orderT.getId(), 3);
					responseMap.put("status", 1);
					responseMap.put("msg", "您的" + rolesT.getRolesName() + "权限申请已通过，请重新登录");
					ParameterTool.writeResponse(response, JsonUtils.toJsonString(responseMap));
				} else {
					RolesOrderT orderT = initRoleOrder(userT.getId(), roleId, rolesT.getRolesName(), organizationId,
							organizationName, organizationType, employeeNum, subUserGroupId, 1, applyType);
					// 增加通知和关联关系
					createRelationAndNotify(orderT, handlerList);
					// 拼装返回参数

					String roleNo = rolesT.getRolesNo();
					if ("R0041".equals(roleNo)) {
						responseMap.put("status", 2);
						responseMap.put("msg", "您的" + rolesT.getRolesName() + "权限申请已提交，请耐心等待管理员审核");
						ParameterTool.writeResponse(response, JsonUtils.toJsonString(responseMap));
						return;
					} else if (!"R0041".equals(roleNo) && organizationType.equals(2)) {
						responseMap.put("status", 2);
						responseMap.put("msg", "您的" + rolesT.getRolesName() + "权限申请已提交，请耐心等待站长审核");
						ParameterTool.writeResponse(response, JsonUtils.toJsonString(responseMap));
						return;
					} else {
						responseMap.put("status", 2);
						responseMap.put("msg", "您的" + rolesT.getRolesName() + "权限申请已提交，请耐心等待管理员审核");
						ParameterTool.writeResponse(response, JsonUtils.toJsonString(responseMap));
						return;
					}
				}
			} else {
				RolesOrderT orderT = initRoleOrder(userT.getId(), roleId, rolesT.getRolesName(), organizationId,
						organizationName, organizationType, employeeNum, subUserGroupId, 2, applyType);
				handleOrder(orderT.getId(), 3);
				ParameterTool.writeSuccessResponse(response);
				return;
			}
		} catch (NumberFormatException e) {
			log.error(e.getMessage(), e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ParameterTool.writeErrorResponse(response);
		} finally {
			redisClientUtils.delkey("applyRole-" + userT.getUserName());
		}
	}

	@Override
	public Boolean addRoleOrder(Long organizationId, String organizationName, Integer organizationType,
			String employeeNum, Long userId, RolesT rolesT, Long userGroupId, Long subUserGroupId,
			List<UserT> handlerList, Integer applyType) {
		if (rolesT.getIsApproval().equals(1)) {
			// 初始化申请权限订单
			RolesOrderT orderT = initRoleOrder(userId, rolesT.getId(), rolesT.getRolesName(), organizationId,
					organizationName, organizationType, employeeNum, subUserGroupId, 1, applyType);
			// 如果申请服务工程师角色，并且employeeNum符合WWID规则，判断是否为真正内部员工
			if (SERVICE_ENGINEER_ROLE_NO.equals(rolesT.getRolesNo())) {
				String adUserId = getAdUserIdByEmployeeNum(employeeNum);
				if (StringUtils.isNotEmpty(adUserId)) {
					// 该员工编号用户名在数据库中不存在
					UserT existUser = loginDao.getUserByUserName(employeeNum);
					if (null != existUser && userId.equals(existUser.getId())) {
						UserT adUser = loginDao.getUserByAdUserId(adUserId);
						// 该AD用户在数据库不存在
						if (null == adUser || orderT.getUserId().equals(adUser.getId())) {
							handleOrder(orderT.getId(), 3);
							return false;
						}
					}
				}
				createRelationAndNotify(orderT, handlerList);
				return true;
			} else {
				createRelationAndNotify(orderT, handlerList);
				return true;
			}
		} else {
			RolesOrderT orderT = initRoleOrder(userId, rolesT.getId(), rolesT.getRolesName(), organizationId,
					organizationName, organizationType, employeeNum, subUserGroupId, 2, applyType);
			handleOrder(orderT.getId(), 3);
			return false;
		}
	}

	@Override
	public List<UserT> getHandlerList(Long organizationId, Integer organizationType, Long userGroupId, Long roleId) {
		List<UserT> handlerList = new ArrayList<>();
		RolesT rolesT = rolesTDao.getRolesById(roleId);
		if (organizationType.equals(1) || rolesT.getRolesNo().equals(MASTER_ROLENO)) {
			String companyIds = null;
			if (rolesT.getRolesNo().equals(MASTER_ROLENO)) {// 如果申请站长角色
				// 判断当前申请的是否是二网，如果是二网，则审批人为所属一网站长
				ServiceStationT serviceStation = serviceStationDao.findServiceStationByID(organizationId + "");
				int relationType = serviceStation.getRelationType() == null ? 1 : serviceStation.getRelationType();// 服务站类型，1-一网，2-二网
				if (relationType == 2) {// 如果是二网，查找所属一网站长作为审批人
					return userTDao.getStationMangerListByChildSSId(organizationId);
				}
				List<Long> companyIdList = rolesDao.getParentCompanyIdsByStationId(organizationId);
				if (CollectionUtils.isNotEmpty(companyIdList)) {
					for (Long id : companyIdList) {
						if (StringUtils.isEmpty(companyIds)) {
							companyIds = id + ",";
						} else {
							companyIds = companyIds + id + ",";
						}
					}
					companyIds = companyIds.substring(0, companyIds.length() - 1);
				} else {
					return handlerList;
				}
			} else {
				companyIds = String.valueOf(organizationId);
			}
			Map<String, Object> queryRolesParam = new HashMap<>();
            queryRolesParam.put("roleId", roleId);
            queryRolesParam.put("companyIds", StringToool.getStringList(companyIds, ","));
            queryRolesParam.put("userGroupId", userGroupId);
			List<Long> handleTList = rolesHandleTDao.selectRoleHandlerIdListByMap(queryRolesParam);
			if (CollectionUtils.isNotEmpty(handleTList)) {
				for (Long handlerId : handleTList) {
					UserT userT = userTDao.selectById(handlerId);
					handlerList.add(userT);
				}
			}
			// 如果是站长，追加如下逻辑增加区域工程师/区域服务经理/福田审核人员审核
			if (rolesT.getRolesNo().equals(MASTER_ROLENO)) {
				// 查询服务商授权渠道
				List<Map<String, Object>> ssRepairList = ssRepairTDao.getSSRepairTByServiceStationID(organizationId);
				if (CollectionUtils.isNotEmpty(ssRepairList)) {
					List<Long> existCompanyList = new ArrayList<>();
					for (Map<String, Object> ssRepairMap : ssRepairList) {
						Long companyId = MapUtils.getLong(ssRepairMap, "CompanyID");
						// 防止单渠道多次授权导致的多次查询
						if (existCompanyList.contains(companyId)) {
							continue;
						} else {
							existCompanyList.add(companyId);
						}
						if (companyId.equals(2L)) {
							// 福田康明斯根据省份查询对应审核人逻辑
							// 查询服务商信息
							Map<String, Object> serviceStationMap = serviceStationDao
									.getServiceStationById(organizationId);
							if (MapUtils.isNotEmpty(serviceStationMap)) {
								// 查询服务商所属省份
								String stationProvince = MapUtils.getString(serviceStationMap, "Province");
								if (StringUtils.isNotEmpty(stationProvince)) {
									// 查询福田管辖表
									List<FotonPositionT> positionTList = fotonPositionTDao
											.selectListByAreaName(stationProvince);
									if (CollectionUtils.isNotEmpty(positionTList)) {
										for (FotonPositionT positionT : positionTList) {
											// 根据管辖手机号，查询app用户
											List<UserT> userTS = loginDao.getUserByPhone(positionT.getPhone());
											handlerList.addAll(userTS);
										}
									}
								}
							}
						} else if (companyId.equals(109L)) {
							// CCEC不追加区域管辖关系的审核人
							continue;
						} else {
							// 通过服务商ID和渠道ID查询对应
							List<UserT> dataHandlerList = positionUserTDao
									.getUserListByServiceStationIdCompanyId(companyId, organizationId);
							if (CollectionUtils.isNotEmpty(dataHandlerList)) {
								handlerList.addAll(dataHandlerList);
							}
						}
					}
				}
			}
		} else {
			// 当为服务站类型或分公司类型，且角色不为站长时，通过站长确定
			Map<String, Object> serviceStationIdMap = new HashMap<>();
			serviceStationIdMap.put("ServiceStationID", organizationId);
			List<UserT> stationMasterList = userTDao.getUserTByServiceStationId(serviceStationIdMap);
			handlerList = stationMasterList;
		}
		return handlerList;
	}

	@Override
	public Long getUserGroupId(Long organizationId, Integer organizationType) {
		Long userGroupId = null;
		if (organizationType.equals(1)) {
			Map<String, Object> groupMap = companyUserGroupRelationDao.getCompanyUserGroup(organizationId);
			userGroupId = (Long) groupMap.get("UserGroupId");
		} else {
			Integer count = rolesDao.getParentCompanyCountByStationId(organizationId);
			if (count > 1) {
				// 该服务站为联合服务站
				userGroupId = rolesDao.getUnionStationUserGroupId();
			} else if (count == 1) {
				// 该服务站位单独授权服务站
				List<Long> userGroupIds = rolesDao.getStationUserGroupIds(organizationId);
				if (CollectionUtils.isNotEmpty(userGroupIds)) {
					userGroupId = userGroupIds.get(0);
				}
				// userGroupId = rolesDao.getStationUserGroupId(organizationId);
			} else {
				log.error("未知用户渠道信息，组织编号：" + organizationId);
			}
		}
		return userGroupId;
	}

	@Override
	public void getApplyOrderList(Map map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		Integer pageNo = Integer.valueOf(map.get("pageNo").toString()) == null ? 1
				: Integer.valueOf(map.get("pageNo").toString());
		Integer pageCount = Integer.valueOf(map.get("pageCount").toString());

		String userId = request.getHeader("userid");
		userId = AESTool.decryptString(userId);// AES解密
		UserT userT = (UserT) redisClientUtils.getObject("userT" + userId);
		PageHelper.startPage(pageNo, pageCount, true);
		List<RolesOrderT> list = rolesOrderTDao.selectApplyList(userT.getId());
		PageInfo info = new PageInfo<>(list);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("totalRecord", info.getTotal());
		List<Map<String, Object>> recordListMap = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(info.getList())) {
			for (Object order : info.getList()) {
				Map<String, Object> orderMap = new HashMap<>();
				RolesOrderT orderT = (RolesOrderT) order;
				orderMap.put("orderId", orderT.getId());
				orderMap.put("roleName", orderT.getRoleName());
				orderMap.put("status", orderT.getStatus());
				orderMap.put("applyTime", orderT.getCreateTime());
				orderMap.put("version", orderT.getVersion());
				if (null != orderT.getHandlerId()) {
					UserT handlerUser = userTDao.selectById(orderT.getHandlerId());
					if (null != handlerUser) {
						orderMap.put("handlerName", handlerUser.getContact());
						orderMap.put("handlerPhone", handlerUser.getPhone());
					}
					if (orderT.getStatus() == 3) {
						orderMap.put("handleMessage", orderT.getRefuseMessage());
					}
				}
				recordListMap.add(orderMap);
			}
		}
		dataMap.put("recordList", recordListMap);
		ParameterTool.writeSuccessResponse(response, dataMap);
	}

	@Override
	public void getRoleOrderList(Map map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		Integer pageNo = MapUtils.getInteger(map, "pageNo", 1);
		Integer pageCount = MapUtils.getInteger(map, "pageCount", 10);

		String userId = request.getHeader("userid");
		userId = AESTool.decryptString(userId);// AES解密
		UserT userT = (UserT) redisClientUtils.getObject("userT" + userId);
		if (null == userT) {
			userT = UserThreadLocal.get();
		}
		// 获取当前用户的角色名称
		Map<String, Object> roleNameMap = rolesTDao.getRoleNamesByUserId(userT.getId());
		// 3.2.0运维需求 区域工程师和站长变更角色后 不能看到原有角色审批的数据
		Integer type = Integer.valueOf(map.get("type").toString());
		Map<String, Object> queryMap = new HashMap<>(2);
		queryMap.put("type", type);
		queryMap.put("userId", userT.getId());
		queryMap.put("keyword", MapUtils.getString(map, "keyword", ""));
		List<Map<String, Object>> list = new ArrayList<>();
		// 当前登录人拥有的角色
		String roleNames = MapUtils.getString(roleNameMap, "RoleNames", "");
		// 角色类型 sql中判断使用
		int roleType = 0;
		// 区域工程师只获取管辖下的服务站站长的申请信息
		if (roleNames.contains("区域工程师")) {
			roleType = 1;
		}
		// 服务商站长只获取本服务站下除了服务商站长以外的角色的申请信息
		if (roleNames.contains("服务商站长")) {
			roleType = 2;
			queryMap.put("organizationId", userT.getServiceStationID());
		}
		queryMap.put("roleType", roleType);
		// newRoleName字段保存该用户除了康明斯服务站用户组下的角色
		List<String> dbuUsergroupHasRoleNameList = rolesDao.getRoleNameListByGroupName("康明斯服务站");
		// 获取App普通用户组下所有角色，这些角色无法看到审核列表
		List<String> appUsergroupHasRoleNameList = rolesDao.getRoleNameListByGroupName("App普通用户组");
		String newRoleName = "";
		String[] roleNameArr = roleNames.split(",");
		if (null != roleNameArr && roleNameArr.length != 0) {
			for (String roleName : roleNameArr) {
				if (!dbuUsergroupHasRoleNameList.contains(roleName)
						&& !appUsergroupHasRoleNameList.contains(roleName)) {
					newRoleName += roleName + ",";
				}
			}
			if (StringUtils.isNotEmpty(newRoleName)) {
				newRoleName = newRoleName.substring(0, newRoleName.length() - 1);
			}
		}
		// 终端用户直接返回空数据给前端，不是终端用户使用原来的sql获取审核记录，获取审核记录后遍历筛选
		PageHelper.startPage(pageNo, pageCount, true);
		if (StringUtils.isNotEmpty(newRoleName)) {
			list = rolesOrderTDao.selectConfirmList(queryMap);
		}
		PageInfo info = new PageInfo<>(list);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("totalRecord", info.getTotal());
		List<Map<String, Object>> recordListMap = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(info.getList())) {
			for (Object order : info.getList()) {
				Map<String, Object> orderMap = new HashMap<>();
				Map<String, Object> orderMaps = (Map<String, Object>) order;
				orderMap.put("orderId", MapUtils.getLong(orderMaps, "ID"));
				orderMap.put("roleName", MapUtils.getString(orderMaps, "RoleName"));
				orderMap.put("status", MapUtils.getInteger(orderMaps, "Status"));
				orderMap.put("name", MapUtils.getString(orderMaps, "Contact"));
				orderMap.put("phone", MapUtils.getString(orderMaps, "Phone"));
				// 申请人申请的服务站名称
				orderMap.put("StationName", MapUtils.getString(orderMaps, "OrganizationName"));
				recordListMap.add(orderMap);
			}
		}
		dataMap.put("recordList", recordListMap);
		ParameterTool.writeSuccessResponse(response, dataMap);
	}

	@Override
	public void getRoleNotifyList(Map map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		Integer pageNo = Integer.valueOf(map.get("pageNo").toString()) == null ? 1
				: Integer.valueOf(map.get("pageNo").toString());
		Integer pageCount = Integer.valueOf(map.get("pageCount").toString());

		String userId = request.getHeader("userid");
		userId = AESTool.decryptString(userId);// AES解密
		UserT userT = (UserT) redisClientUtils.getObject("userT" + userId);
		/**
		 * add 0416 目前日志中都是上面user报空指针
		 */
		if (null == userT) {
			userT = UserThreadLocal.get();
		}
		// 获取当前用户的角色名称
		Map<String, Object> roleNameMap = rolesTDao.getRoleNamesByUserId(userT.getId());
		// 3.2.0运维需求 区域工程师和站长变更角色后 不能看到原有角色审批的数据
		Map<String, Object> queryMap = new HashMap<>();
		// 当前登录人拥有的角色
		String roleNames = MapUtils.getString(roleNameMap, "RoleNames", "");
		// 角色类型 sql中判断使用
		int roleType = 0;
		// 区域工程师只获取管辖下的服务站站长的申请信息
		if (roleNames.contains("区域工程师")) {
			roleType = 1;
		}
		// 服务商站长只获取本服务站下除了服务商站长以外的角色的申请信息
		if (roleNames.contains("服务商站长")) {
			roleType = 2;
			queryMap.put("organizationId", userT.getServiceStationID());
		}
		queryMap.put("roleType", roleType);
		queryMap.put("userId", userT.getId());
		PageHelper.startPage(pageNo, pageCount, true);
		List<Map<String, Object>> notifyMapList = new ArrayList<>();
		// newRoleName字段保存该用户除了康明斯服务站用户组下的角色
		List<String> dbuUsergroupHasRoleNameList = rolesDao.getRoleNameListByGroupName("康明斯服务站");
		// 获取App普通用户组下所有角色，这些角色无法看到审核列表
		List<String> appUsergroupHasRoleNameList = rolesDao.getRoleNameListByGroupName("App普通用户组");
		String newRoleName = "";
		String[] roleNameArr = roleNames.split(",");
		if (null != roleNameArr && roleNameArr.length != 0) {
			for (String roleName : roleNameArr) {
				/*
				 * if (!dbuUsergroupHasRoleNameList.contains(roleName) &&
				 * !appUsergroupHasRoleNameList.contains(roleName)) {
				 * 
				 * }
				 */
				newRoleName += roleName + ",";
			}
			if (StringUtils.isNotEmpty(newRoleName)) {
				newRoleName = newRoleName.substring(0, newRoleName.length() - 1);
			}
		}
		// 登录人为App普通用户组下的角色直接返回空数据给前端，反之使用原来的sql获取审核记录，获取审核记录后遍历筛选
		if (StringUtils.isNotEmpty(newRoleName)) {
			notifyMapList = rolesNotifyRecordTDao.selectListByUserId(queryMap);
			if ((long) (pageNo - 1) * pageCount > notifyMapList.size()) {
				notifyMapList = new ArrayList<>();
			} else if ((long) (pageNo - 1) * pageCount < notifyMapList.size() - pageCount) {
				notifyMapList = notifyMapList.subList((pageNo - 1) * pageCount, (pageNo - 1) * pageCount + pageCount);
			} else {
				notifyMapList = notifyMapList.subList((pageNo - 1) * pageCount, notifyMapList.size());
			}
		}
		PageInfo info = new PageInfo<>(notifyMapList);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("totalRecord", info.getTotal());
		List<Map<String, Object>> recordListMap = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(info.getList())) {
			for (Object order : info.getList()) {
				Map<String, Object> orderMap = new HashMap<>();
				Map<String, Object> notifyMap = (Map) order;
				Long notifyId = Long.valueOf(notifyMap.get("id").toString());
				orderMap.put("id", notifyId);
				orderMap.put("orderId", notifyMap.get("orderId"));
				orderMap.put("roleName", notifyMap.get("roleName"));
				orderMap.put("organizationName", notifyMap.get("organizationName"));
				orderMap.put("status", notifyMap.get("status"));
				Integer isRead = Integer.valueOf(notifyMap.get("isRead").toString());
				orderMap.put("isRead", isRead);
				// 2.5.0 获取权限申请列表后 不标志为已读状态
				/*
				 * if (isRead.equals(0)) { rolesNotifyRecordTDao.readNotifyById(notifyId); }
				 */
				orderMap.put("sendTime", notifyMap.get("sendTime"));

				// 拼装申请人信息
				UserT applyUser = userTDao.selectById((Long) notifyMap.get("userId"));
				orderMap.put("name", applyUser.getContact());
				orderMap.put("phone", applyUser.getPhone());
				orderMap.put("username", applyUser.getUserName());
				orderMap.put("type", applyUser.getType());
				// 拼装审核人信息
				if (null != notifyMap.get("handlerId")) {
					Long handlerId = (Long) notifyMap.get("handlerId");
					List<RolesT> rolesTList = rolesTDao.getRoleListByUserID(handlerId);
					String handlerName = null;
					if (CollectionUtils.isNotEmpty(rolesTList)) {
						for (RolesT rolesT : rolesTList) {
							// 若角色包含站长角色，则直接提示站长姓名
							if (rolesT.getRolesNo().equals("R0041")) {
								UserT handler = userTDao.selectById(handlerId);
								handlerName = handler.getContact();
							}
						}
					}
					if (StringUtils.isEmpty(handlerName)) {
						handlerName = "渠道管理员";
					}
					orderMap.put("handlerName", handlerName);
					orderMap.put("message", notifyMap.get("message"));
				}
				recordListMap.add(orderMap);
			}
		}
		dataMap.put("recordList", recordListMap);
		ParameterTool.writeSuccessResponse(response, dataMap);
	}

	@Override
	public void updateRoleNotifyReadStatus(Map map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		long notifyId = MapUtils.getLongValue(map, "notifyId");
		rolesNotifyRecordTDao.readNotifyById(notifyId);
		ParameterTool.writeSuccessResponse(response, "");
	}

	@Override
	public void getRoleOrder(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		Long orderId = Long.valueOf(map.get("orderId").toString());
		RolesOrderT orderT = rolesOrderTDao.selectByPrimaryKey(orderId);
		if (null != orderT) {
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("orderId", orderT.getId());
			dataMap.put("roleName", orderT.getRoleName());
			dataMap.put("organizationName", orderT.getOrganizationName());
			dataMap.put("version", orderT.getVersion());
			dataMap.put("employeeNum", orderT.getEmployeeNum());
			dataMap.put("status", orderT.getStatus());
			dataMap.put("handlerId", String.valueOf(orderT.getHandlerId()));
			UserT userT = userTDao.selectById(orderT.getUserId());
			dataMap.put("name", userT.getContact());
			dataMap.put("phone", userT.getPhone());
			dataMap.put("username", userT.getUserName());
			dataMap.put("type", userT.getType());
			ParameterTool.writeSuccessResponse(response, dataMap);
		}
	}

	@Override
	@Transactional
	public void approveRoles(Map map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			// Map<String, Object> bodyMap = ParameterTool.getRequestBody(request);
			Map<String, Object> paramMap = map;
			Integer type = Integer.valueOf(map.get("type").toString());
			UserT userT = UserThreadLocal.get();
			if (type.equals(1)) {
				paramMap.put("status", 2);
			} else {
				paramMap.put("status", 3);
				Integer refuseType = Integer.valueOf(map.get("refuseType").toString());
				switch (refuseType) {
				case 1:
					paramMap.put("refuseMessage", "信息不正确");
					break;
				case 2:
					paramMap.put("refuseMessage", "非我司人员");
					break;
				default:
					break;
				}
			}
			paramMap.put("handlerId", userT.getId());
			paramMap.put("handleTime", LocalTimeUtil.getRealCurrentTime());
			paramMap.put("updator", userT.getId());
			paramMap.put("updateTime", LocalTimeUtil.getRealCurrentTime());
			int flag = rolesOrderTDao.updateByMap(paramMap);
			if (flag > 0) {
				Long orderId = Long.valueOf(map.get("orderId").toString());
				// 审批通过
				if (type.equals(1)) {
					Integer handleType = MapUtils.getInteger(map, "handleType", 3);
					RolesOrderT orderT = rolesOrderTDao.selectByPrimaryKey(orderId);
					UserT user = userTDao.selectById(orderT.getUserId());
					long yuanServiceStationID = user.getServiceStationID();
					int yuanIsXgj = userTDao.getXgjRoleList(user.getId());
					handleOrder(orderId, handleType);
					//技师修改服务站和转终端用户同步芯管家服务站
					UserT xinUser = userTDao.selectById(orderT.getUserId());
					long serviceStationID = xinUser.getServiceStationID();
					long usergroupID = xinUser.getUsergroupId();
					int xinIsXgj = userTDao.getXgjRoleList(orderT.getUserId());
					if(yuanIsXgj > 0){
						if(yuanServiceStationID != serviceStationID || usergroupID == 1 || xinIsXgj <= 0){
							cipServiceApi.updateXgjFleetUserId(orderT.getUserId(),yuanServiceStationID);
						}
					} else {
						//添加芯管家管理员
						if(xinIsXgj > 0){
							cipServiceApi.addXgjFleetUserId(orderT.getUserId(),serviceStationID);
						}
					}
					//同步删除cip车辆和车队
					externalDataSynchroService.deleteEsnAndFleet(userT.getId());
				} else {
					// 发送通知
					RolesOrderT orderT = rolesOrderTDao.selectByPrimaryKey(orderId);
					createNotify(orderT, orderT.getUserId(), 1);
				}
			} else {
				ParameterTool.writeResponse(response, 1, "已被其他人处理");
				return;
			}
			ParameterTool.writeSuccessResponse(response);
		} catch (NumberFormatException e) {
			log.error(e.getMessage(), e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ParameterTool.writeErrorResponse(response);
		}
	}

	@Override
	public void adminApproveRoles(Map map) {
		Long userId = MapUtils.getLong(map, "userId");
		if (NumberUtils.isPositiveNum(userId)) {
			UserT userT = userTDao.selectById(userId);
			if (null != userT) {
				UserThreadLocal.set(userT);
				map.put("handleType", 4);
				map.put("version", 0);
				this.approveRoles(map);
			}
		}
	}

	private RolesOrderT initRoleOrder(Long userId, Long roleId, String roleName, Long organizationId,
			String organizationName, Integer organizationType, String employeeNum, Long subUserGroupId, Integer status,
			Integer applyType) {
		RolesOrderT orderT = new RolesOrderT();
		orderT.setUserId(userId);
		orderT.setRoleId(roleId);
		orderT.setRoleName(roleName);
		orderT.setOrganizationId(organizationId);
		orderT.setOrganizationName(organizationName);
		orderT.setOrganizationType(organizationType);
		orderT.setEmployeeNum(employeeNum);
		orderT.setStatus(status);
		orderT.setVersion(0);
		orderT.setFlag(0);
		orderT.setCreator(userId);
		orderT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
		orderT.setSubUserGroupId(subUserGroupId);
		orderT.setApplyType(applyType);
		rolesOrderTDao.insertSelective(orderT);
		return orderT;
	}

	private void createRelationAndNotify(RolesOrderT orderT, List<UserT> handlerList) {
		if (CollectionUtils.isNotEmpty(handlerList)) {
			handlerList.forEach(handler -> {
				RolesOrderHandlerRelationT handlerRelationT = new RolesOrderHandlerRelationT();
				handlerRelationT.setOrderId(orderT.getId());
				handlerRelationT.setHandlerId(handler.getId());
				handlerRelationT.setFlag(0);
				handlerRelationT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
				rolesOrderHandlerRelationTDao.insertSelective(handlerRelationT);

				createNotify(orderT, handler.getId(), 0);
			});
		}
	}

	private Boolean validateVerifyCode(String phone, String verifyCode) {
		String redisCode = redisClientUtils.get("sms" + phone);
		if (StringUtils.isEmpty(redisCode) || !verifyCode.trim().equals(redisCode)) {
			return false;
		} else {
			// redisClientUtils.delkey("sms" + phone);
			return true;
		}
	}

	private void handleOrder(Long orderId, Integer handleType) {
		RolesOrderT orderT = rolesOrderTDao.selectByPrimaryKey(orderId);
		Long userGroupId = getUserGroupId(orderT.getOrganizationId(), orderT.getOrganizationType());
		if (null != userGroupId) {
			Long rolesId = rolesDao.getUserGroupHasRoleId(userGroupId, orderT.getRoleId());
			// 用户组不含有权限
			if (null == rolesId) {
				return;
			}
			UserT userT = userTDao.selectById(orderT.getUserId());
			userT.setUsergroupId(userGroupId);
			if (null == orderT.getSubUserGroupId()) {
				userT.setUsergroupSubId(0);
			} else {
				userT.setUsergroupSubId(orderT.getSubUserGroupId());
			}
			// 如果角色为企业系列
			if (orderT.getOrganizationType() == 1) {
				userT.setServiceStationID(0);
				userT.setDealerLevel(3);
				userT.setCompanyId(orderT.getOrganizationId());
				// 用户为注册用户，且用户的员工编号符合WWID规则,并且用户在AD中存在,将用户信息更新
				if (userT.getType().equals(1)) {
					// 该员工编号在AD用户池
					String adUserId = getAdUserIdByEmployeeNum(orderT.getEmployeeNum());
					if (StringUtils.isNotEmpty(adUserId)) {
						// 该员工编号用户名在数据库中不存在
						UserT existUser = loginDao.getUserByUserName(orderT.getEmployeeNum());
						if (null == existUser || orderT.getUserId().equals(existUser.getId())) {
							UserT adUser = loginDao.getUserByAdUserId(adUserId);
							// 该AD用户在数据库不存在
							if (null == adUser || orderT.getUserId().equals(adUser.getId())) {
								// AzureADTool.deleteAzureUser()
								userT.setAduserId(adUserId);
								userT.setUserName(orderT.getEmployeeNum());
								userT.setType(2);
								userT.setEmployeeNum(orderT.getEmployeeNum());
							}
						}
					}
					// TODO: 2019/5/6 后续完成AD删除用户逻辑
				}
			} else {
				userT.setCompanyId(0);
				userT.setServiceStationID(orderT.getOrganizationId());
				List<Map<String, Object>> mapList = ssRepairTDao
						.getSSRepairTByServiceStationID(orderT.getOrganizationId());
				if (CollectionUtils.isNotEmpty(mapList)) {
					Integer maxType = 0;
					for (Map<String, Object> map : mapList) {
						Integer type = (Integer) map.get("SSType");
						maxType = type > maxType ? type : maxType;
					}
					switch (maxType) {
					case 1:
						userT.setDealerLevel(1);
						break;
					case 2:
						userT.setDealerLevel(2);
						break;
					case 3:
						userT.setDealerLevel(3);
						break;
					default:
						break;
					}

				}
			}
			// 查询数据库角色
			RolesT rolesT = rolesTDao.getRolesById(orderT.getRoleId());
			if (rolesT.getRolesNo().equals("R0041")) {
				deleteStationMaster(orderT.getOrganizationId());
			}
			// 获取原有角色信息
			String preRoles = scanRecordService.getUserRoles(orderT.getUserId());
			// 更新用户信息
			userTDao.updateByPrimaryKeySelective(userT);

			// 当申请更换角色时，删除原有角色信息
			if (orderT.getApplyType().equals(1)) {
				// 删除用户角色关联
				loginDao.delUserRoleRel(String.valueOf(userT.getId()));
			}

			// 赋予用户新角色
			Map<String, Object> paramsMap = new HashMap<>(2);
			paramsMap.put("userID", userT.getId());
			paramsMap.put("rolesID", rolesId);
			loginDao.insertUserRole(paramsMap);

			// 获取最新角色信息
			String nowRoles = scanRecordService.getUserRoles(orderT.getUserId());
			UserT operator = UserThreadLocal.get();
			// 插入修改记录
			scanRecordService.addRecord(handleType, operator, userT, preRoles, nowRoles);
			// 当角色为审批角色时，才给申请用户发送通知
			if (1 == rolesT.getIsApproval()) {
				// 发送通知
				createNotify(orderT, userT.getId(), 1);
			}
		}
	}

	private void deleteStationMaster(Long serviceStationId) {
		Map<String, Object> serviceStationIdMap = new HashMap<>();
		serviceStationIdMap.put("ServiceStationID", serviceStationId);
		List<UserT> stationMasterList = userTDao.getUserTByServiceStationId(serviceStationIdMap);
		if (CollectionUtils.isNotEmpty(stationMasterList)) {
			for (UserT userT : stationMasterList) {
				// 更新用户信息
				userT = initBaseUserGroup(userT);
				userT.setServiceStationID(0L);
				userT.setDealerLevel(0);
				userTDao.updateByPrimaryKeySelective(userT);
				// 更新用户角色
				loginDao.delUserRoleRel(String.valueOf(userT.getId()));
				initBaseRoles(userT);
			}
		}
	}

	private String getAdUserIdByEmployeeNum(String employeeNum) {
		String adUserId = null;
		if (StringUtils.isNotEmpty(employeeNum) && WWID_PATTERN.matcher(employeeNum).matches()) {
			String webClient_id = this.propertiesUtils.getPropertiesValue("webClient_id");
			String webClientSecret = this.propertiesUtils.getPropertiesValue("webClientSecret");
			String tenant = this.propertiesUtils.getPropertiesValue("tenant");
			String innerTenant = this.propertiesUtils.getPropertiesValue("innerTenant");
			// 获取token
			String token = AzureADTool.getManagementToken(tenant, webClient_id, webClientSecret);
			// 查询用户信息
			String userJson = AzureADTool.getUser(employeeNum, innerTenant, token);
			// 用户存在，说明该用户为内部用户
			if (StringUtils.isNotEmpty(userJson)) {
				Map<String, Object> userMap = JsonUtils.toJavaObject(userJson, Map.class);
				adUserId = (String) userMap.get("id");
			}
		}
		return adUserId;
	}

	/**
	 * 发送权限申请通知
	 * 
	 * @param orderT 权限订单信息
	 * @param userId 接收人ID
	 * @param type   发送类型，0-权限申请通知，1，权限审批通知，2-权限取消通知
	 */
	private void createNotify(RolesOrderT orderT, Long userId, Integer type) {
		RolesNotifyRecordT recordT = new RolesNotifyRecordT();
		recordT.setOrderId(orderT.getId());
		recordT.setReceiverId(userId);
		recordT.setType(type);
		recordT.setStatus(orderT.getStatus());
		StringBuffer sb = new StringBuffer();
		if (type == 0) {
			sb.append("您有新的权限审核订单，请查看。");
		} else if (type == 1) {
			sb.append("您的权限申请订单已处理，请查看。");
		} else {
			sb.append("您有权限申请订单已取消，请查看。");
		}
		recordT.setIsRead(0);
		recordT.setSendTime(LocalTimeUtil.getRealCurrentTime());
		recordT.setFlag(0);
		String statusMessage = null;
		RelationShipT relationT = relationShipTDao.getClientIdByUserId(userId);
		if (null != relationT) {
			NotifyUtil.push2Single(relationT.getClientId(), "新审核信息提醒", sb.toString(), 2, sb.toString());
		} else {
			statusMessage = "no relation (ClientId) exist";
		}
		recordT.setStatusMessage(statusMessage);
		rolesNotifyRecordTDao.insertSelective(recordT);
	}

	@Override
	public UserT initBaseUserGroup(UserT userT) {
		long userGroupID = Long.valueOf(propertiesUtils.getPropertiesValue("usergroupID"));
		long userGroupSubID = Long.valueOf(propertiesUtils.getPropertiesValue("usergroupSubID"));
		userT.setUsergroupId(userGroupID);
		userT.setUsergroupSubId(userGroupSubID);
		return userT;
	}

	@Override
	public void initBaseRoles(UserT userT) {
		Long userId = userT.getId();
		Long userGroupId = userT.getUsergroupId();
		// 获取普通用户的权限
		List<Long> roles = rolesTDao.getUserGroupHasRolesIdList(userGroupId, "R0002");
		if (CollectionUtils.isNotEmpty(roles)) {
			roles.forEach(roleId -> {
				Map<String, Object> paramsMap = new HashMap();
				paramsMap.put("userID", userId);
				paramsMap.put("rolesID", roleId);
				loginDao.insertUserRole(paramsMap);
			});
		}
	}

	@Override
	public void initRoles(UserT userT, String roleNo) {
		Long userId = userT.getId();
		Long userGroupId = userT.getUsergroupId();
		// 获取普通用户的权限
		List<Long> roles = rolesTDao.getUserGroupHasRolesIdList(userGroupId, roleNo);
		if (CollectionUtils.isNotEmpty(roles)) {
			roles.forEach(roleId -> {
				Map<String, Object> paramsMap = new HashMap();
				paramsMap.put("userID", userId);
				paramsMap.put("rolesID", roleId);
				loginDao.insertUserRole(paramsMap);
			});
		}
	}

	@Override
	public void getRoleChannelList(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		Long queryCompanyId = MapUtils.getLong(map, "companyId");
		List<Map<String, Object>> channelList = new ArrayList<>();
		if (null != queryCompanyId && !queryCompanyId.equals(0L)) {
			Map<String, Object> channelMap = roleChannelTDao.getRoleChannelByCompanyId(queryCompanyId);
			channelList.add(channelMap);
		} else {
			channelList = roleChannelTDao.getRoleChannelList();
		}
		List<Map<String, Object>> responseList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(channelList)) {
			for (Map<String, Object> channelMap : channelList) {
				Map<String, Object> responseChannelMap = new HashMap<>(3);
				responseChannelMap.put("type", MapUtils.getInteger(channelMap, "Type"));
				responseChannelMap.put("companyType", MapUtils.getInteger(channelMap, "CompanyType", 0));
				responseChannelMap.put("name", MapUtils.getString(channelMap, "Name"));
				Long companyId = MapUtils.getLong(channelMap, "CompanyId");
				if (null != companyId) {
					CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(companyId);
					responseChannelMap.put("organizationId", companyT.getId());
					responseChannelMap.put("organizationName", companyT.getCompanyName());
				}
				responseList.add(responseChannelMap);
			}
		}
		Map<String, Object> result = new HashMap<>(1);
		result.put("roleChannelList", responseList);
		ParameterTool.writeSuccessResponse(response, result);
	}

	@Override
	@Transactional
	public void cancelRole(Map map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		UserT userT = UserThreadLocal.get();
		// 获取用户当日是否已取消申请
		String today = LocalTimeUtil.getRealCurrentTime().substring(0, 10);
		int cancelCount = rolesOrderTDao.selectTodayCancelCountByUserId(userT.getId(), today);
		if (cancelCount > 0) {
			ParameterTool.writeResponse(response, 1, "每天只能撤销一次，如您仍撤销可以联系400");
			return;
		}
		Long roleOrderId = MapUtils.getLong(map, "orderId");
		Integer version = MapUtils.getInteger(map, "version");
		if (NumberUtils.isPositiveNum(roleOrderId)) {
			RolesOrderT rolesOrderT = rolesOrderTDao.selectByPrimaryKey(roleOrderId);
			if (null != rolesOrderT && rolesOrderT.getUserId().equals(userT.getId())) {
				rolesOrderT.setStatus(4);
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("orderId", roleOrderId);
				paramMap.put("status", 4);
				paramMap.put("version", version);
				paramMap.put("handlerId", userT.getId());
				paramMap.put("handleTime", LocalTimeUtil.getRealCurrentTime());
				paramMap.put("updator", userT.getId());
				paramMap.put("updateTime", LocalTimeUtil.getRealCurrentTime());
				int flag = rolesOrderTDao.updateByMap(paramMap);
				if (flag > 0) {
					List<RolesOrderHandlerRelationT> rolesOrderHandlerRelationTS = rolesOrderHandlerRelationTDao
							.selectListByOrderId(roleOrderId);
					if (CollectionUtils.isNotEmpty(rolesOrderHandlerRelationTS)) {
						for (RolesOrderHandlerRelationT relationT : rolesOrderHandlerRelationTS) {
							createNotify(rolesOrderT, relationT.getHandlerId(), 2);
						}
					}
					ParameterTool.writeSuccessResponse(response);
				} else {
					ParameterTool.writeResponse(response, 3, "已被其他人处理");
				}
			} else {
				ParameterTool.writeResponse(response, 2, "无申请信息");
			}
		} else {
			ParameterTool.writeErrorResponse(response, -5);
		}
	}

	@Transactional
	@Override
	public ModelAndView addRoleByUserId(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		long userId = MapUtils.getLongValue(map, "userId", 0); // 要修改的用户主键id
		String roleNo = MapUtils.getString(map, "roleNo", ""); // 要新增的角色
		try {
			if (StringUtils.isEmpty(roleNo) || userId == 0) {
				ParameterTool.writeResponse(response, -5, ApiErrorCode.getInstance().getErrorMsg(-5));
			} else {

				// 查询出当前用户的所有角色
				int isContains = userTDao.isContainsRoleNo(userId, roleNo);
				if (isContains <= 0) {
					Map<String, Object> roleMap = rolesTDao.getRoleByRoleNo(roleNo);
					UserT userT = userTDao.selectById(userId);
					long roleId = MapUtils.getLongValue(roleMap, "ID", 0);
					Map<String, Object> userGroupHasRoleMap = userGroupHasRoleDao.getUserGroupHasRole(roleId,
							userT.getUsergroupId());
					long userGroupHasRoleId = MapUtils.getLongValue(userGroupHasRoleMap, "ID", 0);
					Map<String, Object> insertUserHasRoleMap = new HashMap<>();
					insertUserHasRoleMap.put("userID", userT.getId());
					insertUserHasRoleMap.put("rolesID", userGroupHasRoleId);
					loginDao.insertUserRole(insertUserHasRoleMap);
				}
				ParameterTool.writeSuccessResponse(response);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}

	@Override
	public void getCompanysGuidanz(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		List<Map<String, Object>> companys = companyTDao.getCompanysGuidanz(MapUtils.getString(map, "keywords"));
		ParameterTool.writeSuccessResponse(response, companys);

	}
}
